﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using SailHero.Soft.ESB.Communication.ClientAndServer.Client;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Messages;

namespace HJT212_Protocol_WebHostClient
{
    /// <summary>
    /// Summary description for CommandHandler
    /// </summary>
    public class CommandHandler : IHttpHandler,IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string cmdType = context.Request["cmdType"];
            switch (cmdType)
            {
                case "send":
                    GoSendMsg(context);
                    break;
                case "showmsg":
                    GoShowMsg(context);
                    break;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void GoSendMsg(HttpContext context)
        {
            try
            {
                var obj = context.Session["client"];
                if (obj == null) return;
                IClient client = (IClient)context.Session["client"];
                string toMN = context.Request["selcedMN"];
                if (string.IsNullOrEmpty(toMN)) return;
                string sendMsg = context.Request["txtMsgToSend"];
                if (string.IsNullOrEmpty(sendMsg)) return;

                TextMessage Tmsg = new TextMessage(sendMsg);
                Tmsg.FromMN = string.Format("{0}{1}", client.MN, "");
                Tmsg.To = toMN;
                client.SendMessage(Tmsg);
                context.Response.Write("发送成功");
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }

        private void GoShowMsg(HttpContext context)
        {
            try
            {
                var obj = context.Session["msgToshow"];
                if (obj == null) return;
                string msgToshow = (string)obj;
                if (string.IsNullOrEmpty(msgToshow)) return;
                context.Response.Write(msgToshow);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}